<?php

require_once 'Solar/Base.php';
require_once 'Domain51/Util/String/Hex.php';
require_once 'Domain51/Service/Amazon/Util/Header.php';

class Domain51_Service_Amazon_Util_AuthorizationGenerator extends Solar_Base
{
    private $_data = array();
    private $_header = null;
    
    function setHeader(Domain51_Service_Amazon_Util_Header $header) 
    {
        $this->_header = $header;
    }
    
    function generate() 
    {
        return "AWS {$this->_config['access_key']}:{$this->generateHash()}";
    }
    
    function generateHash() 
    {
        $stringToSign = "{$this->_header->getType()}\n" .
            "{$this->_header->get('Content-Md5')}\n" .
            "{$this->_header->get('Content-Type')}\n" .
            "{$this->_header->get('Date')}\n";
        
        foreach ($this->_header->toArray('Amz') as $header => $value) {
            $stringToSign .= strtolower($header) . ':' . $value . "\n";
        }
        
        //var_dump(strpos($this->_header->getURL(), '?'));
        if (strpos($this->_header->getURL(), '?') === false) {
            $url = $this->_header->getURL();
        } else {
            $url = substr($this->_header->getUrl(), 0, strpos($this->_header->getURL(), '?'));
        }
        //var_dump($url);exit;
        $stringToSign .= $url;
        
        $hash = hash_hmac('sha1', $stringToSign, $this->_config['secret_key']);
        
        $hex = new Domain51_Util_String_Hex();
        return $hex->toBase64($hash);
    }
}

?>